package com.plum.admin.modules.quartz.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.common.exception.BaseException;
import com.plum.admin.common.util.R;
import com.plum.admin.modules.quartz.entity.SysQuartzJob;
import com.plum.admin.modules.quartz.service.ISysQuartzJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.plum.admin.base.BaseController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 子丶沫
 * @since 2021-09-22
 */
@RestController
@RequestMapping("/sys/quartz/")
@Api(tags = "定时任务管理")
public class SysQuartzJobController extends BaseController {
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private ISysQuartzJobService quartzJobService;

    @GetMapping
    @PreAuthorize("hasAnyAuthority('sys:quartz:list')")
    @ApiOperation("定时任务")
    public R<Object> findQuartzList(Integer page, Integer pageSize, SysQuartzJob quartzJob){
        return R.ok(quartzJobService.page(new Page<>(page,pageSize), Wrappers.lambdaQuery()));
    }
    @PostMapping
    @ApiOperation("添加定时任务")
    @PreAuthorize("hasAnyAuthority('sys:quartz:save')")
    public R<Object> addQuartz(@RequestBody SysQuartzJob quartzJob){
        quartzJobService.addJob(quartzJob.getJobClassName(),quartzJob.getCronExpression(),quartzJob.getParameter());
        return R.ok(quartzJobService.save(quartzJob));
    }
    @PutMapping
    @ApiOperation("修改定时任务")
    @PreAuthorize("hasAnyAuthority('sys:quartz:update')")
    public R<Object> editQuartz(@RequestBody SysQuartzJob quartzJob){
        quartzJobService.deleteJob(quartzJob.getJobClassName());
        quartzJobService.addJob(quartzJob.getJobClassName(),quartzJob.getCronExpression(), quartzJob.getParameter());
        return R.ok(quartzJobService.updateById(quartzJob));
    }
    @DeleteMapping
    @ApiOperation("删除定时任务")
    @PreAuthorize("hasAnyAuthority('sys:quartz:delete')")
    public R<Object> deleteJob(String ids){
        List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        for(String id:idList){
            SysQuartzJob quartzJob = quartzJobService.getById(id);
            quartzJobService.deleteJob(quartzJob.getJobClassName());
            quartzJobService.removeById(id);
        }
        return R.ok();
    }
    @PostMapping("/pauseJob/{id}")
    @ApiOperation("暂停定时任务")
    @PreAuthorize("hasAnyAuthority('sys:quartz:pause')")
    public R<Object> pauseJob(@PathVariable String id){
        SysQuartzJob quartzJob = quartzJobService.getById(id);
        try {
            scheduler.pauseJob(JobKey.jobKey(quartzJob.getJobClassName()));
        } catch (SchedulerException e) {
            return R.error("暂停定时任务失败");
        }
        quartzJob.setStatus(Constant.STATUS_DISABLED);
        return R.ok(quartzJobService.updateById(quartzJob));
    }
    @PostMapping("/startJob/{id}")
    @ApiOperation("开始定时任务")
    @PreAuthorize("hasAnyAuthority('sys:quartz:start')")
    public R<Object> startJob(@PathVariable String id){
        SysQuartzJob quartzJob = quartzJobService.getById(id);
        try {
            scheduler.resumeJob(JobKey.jobKey(quartzJob.getJobClassName()));
        } catch (SchedulerException e) {
            return R.error("开始定时任务失败");
        }
        quartzJob.setStatus(Constant.STATUS_NORMAL);
        return R.ok(quartzJobService.updateById(quartzJob));
    }
}
